/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.TrainActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.SearchThemeActivity;
import com.shwread.android.qysw.activity.TrainExamCommonWebActivity;
import com.shwread.android.qysw10000227.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.TrainExamContentView1;
import com.shwread.android.ui.widget.TrainExamContentView1.TrainExamContentViewListener;
import com.shwread.android.ui.widget.TrainExamModelView;
import com.shwread.android.ui.widget.TrainExamModelView.OnModuleSelectedListener;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.Mode;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.bean.TrainIndexBean;
import logic.bean.TrainIndexModel;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.logutil.LogUtil;


/**
 * @Project： Shwread
 * @Title：TrainingExamPage
 * @Description：考试培训系统模块
 * @Author：wayne
 * @Date：2015年3月23日上午9:56:14
 */
public class NewTrainingExamPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener,
        OnModuleSelectedListener
{
	public static boolean              updateData = false;
	private static String              Tag         = "TrainExam";
	private static Rect                ViewPagerRect;
	private static NewTrainingExamPage instance;
	//模块
	TrainExamModelView                 modelView;
	//模块内容
	TrainExamContentView1               examContent;
	private boolean                    isLastSuccess;
	private LinearLayout               contentLinearLayout;
	private PullToRefreshScrollView    contentView;
	//加载动画
	private View                       loadingView;
	private ImageView                  loadingImg, gotoTopImg;
	private AnimationDrawable          animationDrawable;
	//顶部菜单
	private TextView                   tvTitle;
	private Button                     btnBack, btnSearch;
	private ImageView                  ivPersion;
	//banner
	private HashMap<Integer, View>     views;
	private QYViewPager                vpPager;
	private ViewGroup                  vgPoints;
	private List<BannerInfo>           banners;
	private ViewPagerAdapter           pagerAdapter;
	Runnable action = new Runnable()
	                {
		                @Override
		                public void run() {
			                int currentItem = vpPager.getCurrentItem();
			                currentItem++;
			                if (currentItem >= pagerAdapter.getCount())
			                {
				                currentItem = 0;
			                }
			                vpPager.setCurrentItem(currentItem);
		                }
	                };
	private int                        currentType = -1;
	
	public NewTrainingExamPage(MainActivity t) {
		super(t);
	}

	public static NewTrainingExamPage getInstance(MainActivity bActivity) {
		if (instance == null)
		{
			instance = new NewTrainingExamPage(bActivity);
		}
		else
		{
			instance.setActivity(bActivity);
		}
		return instance;
	}
	
	public static void destroy() {
		if (instance != null)
		{
			instance.dispose();
			instance = null;
		}
	}
	
	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.new_trainingexam_lay, null);

		initView();
		setListener();
		QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).setTrainIndexCid("");
		TrainActionHelp.qryTrainIndexForClient(bActivity, "y", new GetTrainIndexAction());
		return curMyView;
	}
	
	void initView() {
		contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.new_trainexam_view);
		PullToRefreshUtil.initLabel(context, contentView);
		contentLinearLayout = (LinearLayout) curMyView.findViewById(R.id.ll_newtrainexam_contentview);
		//加载动画
		loadingView = curMyView.findViewById(R.id.common_loading_layout);
		loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);
		updateLoadingView(0);
		//顶部菜单
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		tvTitle.setText(R.string.maintab_train);
		btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.GONE);
		ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
		ivPersion.setVisibility(View.VISIBLE);
		btnSearch = (Button) curMyView.findViewById(R.id.common_header_search);
		btnSearch.setVisibility(View.VISIBLE);
		//banner
		banners = new ArrayList<BannerInfo>();
		views = new HashMap<Integer, View>();
		vpPager = (QYViewPager) curMyView.findViewById(R.id.enterprise_head_pager);
		vgPoints = (ViewGroup) curMyView.findViewById(R.id.enterprise_head_points);
		// 获取ViewPager在屏幕的位置
		final ViewTreeObserver observer = vpPager.getViewTreeObserver();
		OnGlobalLayoutListener global = new OnGlobalLayoutListener()
		{
			@Override
			public void onGlobalLayout() {
				if (ViewPagerRect == null)
				{
					ViewPagerRect = new Rect();
					vpPager.getGlobalVisibleRect(ViewPagerRect);
				}
			}
		};
		observer.addOnGlobalLayoutListener(global);

		//模块
		modelView = new TrainExamModelView(bActivity, new ArrayList<TrainIndexModel>());
		//模块内容
		examContent = new TrainExamContentView1(bActivity);
		examContent.setActivity(bActivity);
		examContent.setTrainExamContentViewListener(new TrainExamContentViewListener()
		{

			@Override
			public void OnLoadDataCompleted(int flag) {
				modelView.setCanSwitchModule(true);
				if (flag == 1)
				{ //首次装载
					contentView.scrollTo(0, 0);
					contentView.getRefreshableView().scrollTo(0, 0);
					contentView.onRefreshComplete();
				}
				else if (flag == 2)
				{//装载更多
					contentView.onRefreshComplete();
				}
			}
		});

	}
	
	void setListener() {
		//		btnBack.setOnClickListener(this);
		ivPersion.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		vpPager.setOnPageChangeListener(new PagerChangeListener());
		pagerAdapter = new ViewPagerAdapter(bActivity, views, new BannerClick());
		vpPager.setAdapter(pagerAdapter);
		contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (contentView.isHeaderShown())
				{ //下拉刷新
					modelView.setCanSwitchModule(false);
					refresh();
				}
				else if (contentView.isFooterShown())
				{ //上拉加载
					loadMore();
				}
			}
		});
	}
	
	//下拉刷新
	private void refresh() {
		if (currentType != -1)
		{
			examContent.showModelData(currentType, 2);
		}
		else
		{
			modelView.setCanSwitchModule(true);
			contentView.onRefreshComplete();
		}
	}
	
	//上拉加载更多
	private void loadMore() {

		if (examContent.getDataSize() == 0)
		{
			PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
		}
		else
		{
			if (examContent.getHasMore())
			{
				//加载下一页
				examContent.getNextPage();
				return;
			}
			else
			{
				//没有更多了， 所以不再加载下一页
				PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
			}
		}
		contentView.onRefreshComplete();

	}
	
	@Override
	public int enter(IUIPage<?> arg0) {
		if (NetworkUtil.isNetAvailable(bActivity))
		{
			//			if (!isLastSuccess) updateLoadingView(0);
			if (currentType == -1)
			{
				contentView.getRefreshableView().scrollTo(0, 0);
			}
			gotoTop();
		}
		else
		{
			new NoNetDialog(bActivity).show();
		}
		return 0;
	}
	
	@Override
	public int leave(IUIPage<?> arg0) {
		return 0;
	}
	
	@Override
	public void notifyView(int arg0, Bundle arg1) {
		switch (arg0) {
			case DefaultConsts.REFRESH_TRAINEXAM:
				break;
			case DefaultConsts.PAGE_ONRESUME_CODE:
				if (updateData)
				{
					updateData = false;
					refresh();
				}
				break;
			default:
				break;
		}
	}
	
	@Override
	public void setStatus(int arg0) {

	}
	
	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		return null;
	}
	
	@Override
	public void dispose() {
		if (null != banners) banners.removeAll(banners);
		super.dispose();
		if (null != vpPager && null != action)
		{
			vpPager.removeCallbacks(action);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				handleBack();
				break;
			case R.id.common_header_persion:
				bActivity.goPersonalActivity();
				break;
			case R.id.common_header_search:
				Intent intent = new Intent(bActivity, SearchThemeActivity.class);
				bActivity.startActivity(intent);
				break;
			default:
				break;
		}
	}
	
	/*************************** 首页相关end ********************************************************/
	/****************************** banner相关start ***********************************************/
	//获取banner action
	//	private QryTrainIndexBannerAction bannerAction;
	
	/** 回到顶部 */
	private void gotoTop() {
		examContent.post(new Runnable()
		{
			@Override
			public void run() {
				contentView.getRefreshableView().scrollTo(0, 0);
			}
		});
	}
	
	void initBannerView() {
		if (banners.size() == 0) return;
		vgPoints.removeAllViews();
		for (int i = 0; i < banners.size() - 2; i++)
		{
			View view = bActivity.getLayoutInflater().inflate(R.layout.banner_grid_item, null);
			vgPoints.addView(view);
		}
		vpPager.setCurrentItem(1);
		setViewPoint();
		pagerAdapter.notifyDataSetChanged();
		startScroll();
	}
	
	private void startScroll() {
		if (banners.size() <= 1) return;
		vpPager.removeCallbacks(action);
		vpPager.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);
	}
	
	private void setViewPoint() {
		for (int i = 0; i < vgPoints.getChildCount(); i++)
		{
			View view = vgPoints.getChildAt(i);
			ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

			if (i == vpPager.getCurrentItem() - 1)
			{
				img.setBackgroundResource(R.drawable.banner_grid_cur);
			}
			else
			{
				img.setBackgroundResource(R.drawable.banner_grid);
			}
		}
	}
	
	// TODO 点击Banner
	private void clickBanner(BannerInfo info) {
		switch (info.getType()) {
			case BannerInfo.TYPE_BANNER:

				break;
			case BannerInfo.TYPE_BOOKS:

				break;
			case BannerInfo.TYPE_BOOKSURL:
				bActivity.goBookDetailActivity(info.getBooks());
				break;
			case BannerInfo.TYPE_URL:
				//isTrain为1代表是培训的banner
				if (info.getIsTrain() == 1)
				{
					String cid = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getTrainIndexCid();
					Intent intent = new Intent(bActivity, TrainExamCommonWebActivity.class);
					intent.putExtra(DefaultConsts.title_s, " 详情");
					intent.putExtra(DefaultConsts.req_url_s, TrainActionHelp.getUrl() + info.getContent() + "?trainId=" + info.getTrainId() + "&cid=" + cid);
					bActivity.startActivity(intent);
				}
				else bActivity.goWebViewActivity(info);
				break;
		}
	}
	
	/**
	 * 首次进入page加载动画
	 *
	 * @param flag
	 *            0:加载中，1：加载完成，-1：加载失败
	 */
	private void updateLoadingView(int flag) {
		switch (flag) {
			case -1:
				loadingView.setVisibility(View.VISIBLE);
				contentView.setVisibility(View.GONE);
				if (animationDrawable != null && animationDrawable.isRunning())
				{
					animationDrawable.stop();
				}
				loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
				break;
			case 0:
				loadingView.setVisibility(View.VISIBLE);
				contentView.setVisibility(View.GONE);
				loadingImg.setBackgroundResource(R.drawable.home_progress);
				animationDrawable = (AnimationDrawable) loadingImg.getBackground();
				animationDrawable.start();
				break;
			case 1:
				loadingView.setVisibility(View.GONE);
				contentView.setVisibility(View.VISIBLE);
				break;
		}
	}
	
	//模块选中
	@Override
	public void moduleSelected(TrainIndexModel model) {
		//		PullToRefreshUtil.initLabel(context, contentView);
		contentView.getRefreshableView().scrollTo(0, 0);
		PullToRefreshUtil.initLabel(context, contentView);
		currentType = model.type;
		examContent.showModelData(model.getType(), 1);
		// 在线考试去掉上拉加载
		if (model.type == 3) {
			contentView.setMode(Mode.PULL_FROM_START);
		} else {
			contentView.setMode(Mode.BOTH);
		}
	}
	
	@Override
	public void onError(String error) {

	}
	
	/*************************** 首页相关start ********************************************************/
	//	private QryTrainIndexForClientAction trainIndexAction;

	private class GetTrainIndexAction
	        extends
	        ObjectHttpResponseHandler<TrainIndexBean>
	{

		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			LogUtil.d(Tag, responseString);
		}

		@Override
		public void onSuccess(int statusCode, Header[] headers, final TrainIndexBean object, String responseString) {
			bActivity.getUIHandler().post(new Runnable()
			{

				@Override
				public void run() {
					QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).setTrainIndexCid(object.cid);
					modelView = new TrainExamModelView(bActivity, object.moduleList);
					modelView.setOnModuleSelectedListener(NewTrainingExamPage.this);
					// 传模块数据
					examContent.setModuleList(object.moduleList);
					modelView.setBaseActivity(bActivity);
					modelView.setCanSwitchModule(true);
					// 重新加载第一个模块
					examContent.showModelData(1, 1);
					contentLinearLayout.addView(modelView);
					contentLinearLayout.addView(examContent);
					TrainActionHelp.qryTrainIndexBanner(bActivity, object.cid, new GetBannerAction());

				}
			});
		}

		@Override
		public Type getType() {
			return new TypeToken<TrainIndexBean>()
			{
			}.getType();
		}

	}
	
	/****************************** banner相关end ****************************************************/

	/** 获取企业专区Banner数据 */
	private class GetBannerAction
	        extends
	        ObjectHttpResponseHandler<List<BannerInfo>>
	{

		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			bActivity.getUIHandler().post(new Runnable()
			{
				@Override
				public void run() {
					updateLoadingView(-1);
				}
			});
			isLastSuccess = false;

		}

		@Override
		public void onSuccess(int statusCode, Header[] headers, List<BannerInfo> object, String responseString) {

			banners.clear();
			if (object.size() <= 1)
			{
				banners = object;
			}
			else
			{
				banners.add(object.get(object.size() - 1));
				banners.addAll(object);
				banners.add(object.get(0));
			}
			System.out.println("企业专区banner obj:" + banners.toString());
			bActivity.getUIHandler().post(new Runnable()
			{
				@Override
				public void run() {
					if (banners.size() > 0)
					{
						pagerAdapter.setData(banners);
						initBannerView();
					}
					updateLoadingView(1);
					gotoTop();
				}
			});

		}

		@Override
		public Type getType() {
			return new TypeToken<List<BannerInfo>>()
			{
			}.getType();
		}
	}
	
	private class PagerChangeListener
	        implements
	        OnPageChangeListener
	{
		@Override
		public void onPageScrollStateChanged(int state) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int i) {
			int pageIndex = i;
			if (i == 0)
			{
				// 当视图在第一个时，将页面号设置为图片的最后一张。
				pageIndex = banners.size() - 2;
			}
			else if (i == banners.size() - 1)
			{
				// 当视图在最后一个是,将页面号设置为图片的第一张。
				pageIndex = 1;
			}
			if (i != pageIndex)
			{
				vpPager.setCurrentItem(pageIndex, false);
			}
			setViewPoint();
			startScroll();
		}
	}
	
	private class BannerClick
	        implements
	        BannerOnClickListener
	{
		@Override
		public void click(BannerInfo info) {
			clickBanner(info);
		}
	}
}
